#include "iap/include/iap_udp.h"
#include <QThread>
#include <QTime>

int32_t udp_read(uint8_t * pdata, int32_t len)
{
    return 0;
}

int32_t udp_write(uint8_t * pdata, int32_t len)
{
    return 0;
}


IapUdp::IapUdp()
    : __udpsock()
    , __localIp()
    , __sendIp()
    , __localPort(0)
    , __sendPort(0)
{
    // PASS
}

bool IapUdp::BindLocalAddr(QHostAddress ip, quint16 port)
{
    __localIp   = ip;
    __localPort = port;
    return __udpsock.bind(__localIp, __localPort,  QUdpSocket::DefaultForPlatform);
}
void IapUdp::SetSendAddr(QHostAddress ip, quint16 port)
{
    __sendIp   = ip;
    __sendPort = port;
}

qint64  IapUdp::Read(char * data, qint64 maxSize, QHostAddress * ip, quint16 * port, int32_t to)
{
    QTime ti = QTime::currentTime().addMSecs(to);
    qint64 len = 0;
    do {
        if (__udpsock.hasPendingDatagrams()) {
            len = __udpsock.readDatagram(data, maxSize, ip, port);
        } else {
            QThread::msleep(10);
        }
    } while(len <= 0 && QTime::currentTime() < ti);

    if (len < 0) {
        len = 0;
    }
    return len;
}

qint64  IapUdp::Write(QByteArray data)
{
    qint64 len = 0;
    len =  __udpsock.writeDatagram(data, __sendIp, __sendPort);
    if (len < 0) {
        len = 0;
    }
//    __udpsock.waitForBytesWritten();
    return len;
}

void IapUdp::Refresh()
{
    if (__udpsock.isOpen()) {
        __udpsock.close();
        qDebug() << __FILE__ << __LINE__ << __func__;
    } else {
        qDebug() << __FILE__ << __LINE__ << __func__;
    }
    if (__udpsock.bind(__localIp, __localPort,  QUdpSocket::DefaultForPlatform)) {
        qDebug() << __FILE__ << __LINE__ << __func__;
    } else {
        qDebug() << __FILE__ << __LINE__ << __func__;
    }
}

void IapUdp::Close()
{
    __udpsock.close();
}
